package menu

import (
	"context"
	"go-zero-project/common/excption"
	"go-zero-project/services/user/api/constans"
	"go-zero-project/services/user/api/internal/svc"
	"go-zero-project/services/user/api/internal/types"
	"go-zero-project/services/user/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type InfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMenuInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InfoLogic {
	return &InfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *InfoLogic) MenuInfo(req *types.MenuInfoReq) (resp *types.MenuInfoResp, err error) {
	// 1.builder rpc request
	infoReq := pb.MenuInfoReq{MenuId: req.MenuId}
	// 2.request rpc
	infoResp, err := l.svcCtx.UserCenterClient.MenuInfo(l.ctx, &infoReq)
	if err != nil {
		return nil, err
	}
	// 3.return obj
	resp = new(types.MenuInfoResp)
	menuArr := l.loopMenuArr(infoResp)
	if len(menuArr) < 0 {
		return nil, excption.NewErrCode(constans.MenuNoExistError)
	}
	return &types.MenuInfoResp{MenuId: infoResp.MenuId,
		ParentId: infoResp.ParentId,
		Name:     infoResp.Name,
		Url:      infoResp.Url,
		Perms:    infoResp.Perms,
		MenuType: int(infoResp.MenuType),
		Icon:     infoResp.Icon,
		OrderNum: int(infoResp.OrderNum),
		List:     menuArr}, nil
}

func (l *InfoLogic) loopMenuArr(info *pb.MenuInfoResp) []types.MenuInfoResp {
	var navArr []types.MenuInfoResp
	list := info.List
	if len(list) > 0 {
		for _, v := range list {
			loopMenuInfo := types.MenuInfoResp{
				MenuId:   v.MenuId,
				ParentId: v.ParentId,
				Name:     v.Name,
				Url:      v.Url,
				Perms:    v.Perms,
				MenuType: int(v.MenuType),
				Icon:     v.Icon,
				OrderNum: int(v.OrderNum),
			}
			menuInArr := l.loopMenuArr(v)
			loopMenuInfo.List = menuInArr
			navArr = append(navArr, loopMenuInfo)
		}
	}

	return navArr

}
